package com.ruoyi.ai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.device.mapper.DeviceInfoMapper;
import com.ruoyi.device.domain.DeviceInfo;
import com.ruoyi.fault.mapper.FaultAssignMapper;
import com.ruoyi.fault.mapper.FaultReportMapper;
import com.ruoyi.fault.mapper.FaultRepairMapper;
import com.ruoyi.fault.domain.FaultAssign;
import com.ruoyi.fault.domain.FaultReport;
import com.ruoyi.fault.domain.FaultRepair;
import com.ruoyi.maintenance.mapper.MaintenanceAssignMapper;
import com.ruoyi.maintenance.mapper.MaintenancePlanMapper;
import com.ruoyi.maintenance.mapper.MaintenanceRecordMapper;
import com.ruoyi.maintenance.domain.MaintenancePlan;
import com.ruoyi.maintenance.domain.MaintenanceRecord;
import com.ruoyi.maintenance.domain.MaintenanceAssign;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ai")
public class AiChatController {

    @Autowired
    private ChatClient chatClient;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private FaultReportMapper faultReportMapper;
    @Autowired
    private FaultRepairMapper faultRepairMapper;
    @Autowired
    private FaultAssignMapper faultAssignMapper;
    @Autowired
    private MaintenancePlanMapper maintenancePlanMapper;
    @Autowired
    private MaintenanceRecordMapper maintenanceRecordMapper;
    @Autowired
    private MaintenanceAssignMapper maintenanceAssignMapper;

    private static final String DEFAULT_SYSTEM_PROMPT = "你是我们变电站技术室小组的系统助手。";
    private static final String CHAT_HISTORY_ATTRIBUTE = "chatHistory";

    @GetMapping("/chat")
    public AjaxResult generate(
            @RequestParam(value = "message", defaultValue = "Tell me a message") String message,
            @RequestParam(value = "systemPrompt", required = false) String systemPrompt,
            HttpSession session) {
        try {
            // 获取或创建会话中的聊天历史记录
            List<String> chatHistory = (List<String>) session.getAttribute(CHAT_HISTORY_ATTRIBUTE);
            if (chatHistory == null) {
                chatHistory = new ArrayList<>();
            }

            // 构建完整提示信息
            String fullPrompt = buildFullPrompt(message, systemPrompt, chatHistory);

            // 生成 AI 回应
            String response = chatClient.prompt(fullPrompt).call().content().trim();

            // 将用户消息和 AI 响应添加到聊天历史记录
            chatHistory.add("User: " + message);
            chatHistory.add("AI: " + response);

            // 更新会话中的聊天历史记录
            session.setAttribute(CHAT_HISTORY_ATTRIBUTE, chatHistory);

            return AjaxResult.success(response);
        } catch (Exception e) {
            return AjaxResult.error("AI处理失败：" + e.getMessage());
        }
    }

    private String buildFullPrompt(String message, String systemPrompt, List<String> chatHistory) {
        StringBuilder fullPromptBuilder = new StringBuilder();

        // 添加系统提示语
        if (systemPrompt != null && !systemPrompt.isEmpty()) {
            fullPromptBuilder.append(systemPrompt).append("\n\n");
        } else {
            fullPromptBuilder.append(DEFAULT_SYSTEM_PROMPT).append("\n\n");
        }

        // 查询所有设备基本信息并添加到提示词中
        List<DeviceInfo> deviceInfos = deviceInfoMapper.selectDeviceInfoList(new DeviceInfo());
        if (!deviceInfos.isEmpty()) {
            fullPromptBuilder.append("以下是可用的设备基本信息（未查询到的数据库的数据不用展示）：\n");
            for (DeviceInfo info : deviceInfos) {
                fullPromptBuilder.append("- 设备ID: ").append(info.getId()).append("\n")
                        .append(" 设备名称: ").append(info.getDeviceName()).append("\n")
                        .append("  型号: ").append(info.getModel()).append("\n")
                        .append("  规格: ").append(info.getSpecification()).append("\n")
                        .append("  制造商: ").append(info.getManufacturer()).append("\n")
                        .append("  供应商: ").append(info.getSupplier()).append("\n")
                        .append("  采购时间: ").append(info.getPurchaseDate() != null ? info.getPurchaseDate().toString() : "无").append("\n")
                        .append("  安装位置: ").append(info.getLocation()).append("\n")
                        .append("  状态: ").append(info.getStatus()).append("\n")
                        .append("  当前值: ").append(info.getCurrentValue()).append("\n")
                        .append("  描述: ").append(info.getDescription()).append("\n")
                        .append("  创建时间: ").append(info.getCreateTime()).append("\n")
                        .append("  更新时间: ").append(info.getUpdateTime()).append("\n")
                        .append("  创建人: ").append(info.getCreateBy()).append("\n")
                        .append("  更新人: ").append(info.getUpdateBy()).append("\n")
                        .append("\n");
            }
        }

        // 查询所有故障报修记录
        List<FaultReport> faultReports = faultReportMapper.selectFaultReportList(new FaultReport());
        if (!faultReports.isEmpty()) {
            fullPromptBuilder.append("以下是最近的故障报修记录：\n");
            for (FaultReport report : faultReports) {
                fullPromptBuilder.append("- 报修ID: ").append(report.getId()).append("\n")
                        .append("  设备ID: ").append(report.getDeviceId()).append("\n")
                        .append("  故障标题: ").append(report.getFaultTitle()).append("\n")
                        .append("  故障描述: ").append(report.getFaultDesc()).append("\n")
                        .append("  报修人: ").append(report.getReportBy()).append("\n")
                        .append("  报修时间: ").append(report.getReportTime() != null ? report.getReportTime().toString() : "无").append("\n")
                        .append("  状态: ").append(report.getStatus()).append("\n")
                        .append("\n");
            }
        }

        // 查询所有故障处理记录
        List<FaultRepair> faultRepairs = faultRepairMapper.selectFaultRepairList(new FaultRepair());
        if (!faultRepairs.isEmpty()) {
            fullPromptBuilder.append("以下是故障处理记录：\n");
            for (FaultRepair repair : faultRepairs) {
                fullPromptBuilder.append("- 处理ID: ").append(repair.getId()).append("\n")
                        .append("  报修ID: ").append(repair.getReportId()).append("\n")
                        .append("  处理描述: ").append(repair.getRepairDesc()).append("\n")
                        .append("  处理方法: ").append(repair.getRepairMethod()).append("\n")
                        .append("  处理结果: ").append(repair.getRepairResult()).append("\n")
                        .append("  处理人: ").append(repair.getRepairBy()).append("\n")
                        .append("  状态: ").append(repair.getStatus()).append("\n")
                        .append("  开始时间: ").append(repair.getStartTime() != null ? repair.getStartTime().toString() : "无").append("\n")
                        .append("  结束时间: ").append(repair.getEndTime() != null ? repair.getEndTime().toString() : "无").append("\n")
                        .append("\n");
            }
        }

        // 查询所有维修人员分配记录
        List<FaultAssign> faultAssigns = faultAssignMapper.selectFaultAssignList(new FaultAssign());
        if (!faultAssigns.isEmpty()) {
            fullPromptBuilder.append("以下是维修人员分配记录：\n");
            for (FaultAssign assign : faultAssigns) {
                fullPromptBuilder.append("- 分配ID: ").append(assign.getId()).append("\n")
                        .append("  报修ID: ").append(assign.getRepairId()).append("\n")
                        .append("  用户ID: ").append(assign.getUserId()).append("\n")
                        .append("  分配类型: ").append(assign.getAssignType()).append("\n") // 1-负责人,2-实施人
                        .append("\n");
            }
        }

        // 查询所有维护计划记录
        List<MaintenancePlan> maintenancePlans = maintenancePlanMapper.selectMaintenancePlanList(new MaintenancePlan());
        if (!maintenancePlans.isEmpty()) {
            fullPromptBuilder.append("以下是维护计划：\n");
            for (MaintenancePlan plan : maintenancePlans) {
                fullPromptBuilder.append("- 计划ID: ").append(plan.getId()).append("\n")
                        .append("  计划名称: ").append(plan.getPlanName()).append("\n")
                        .append("  设备ID: ").append(plan.getDeviceId()).append("\n")
                        .append("  计划类型: ").append(plan.getPlanType()).append("\n") // 1-定期维护,2-预防性维护,3-临时维护
                        .append("  开始日期: ").append(plan.getStartDate() != null ? plan.getStartDate().toString() : "无").append("\n")
                        .append("  结束日期: ").append(plan.getEndDate() != null ? plan.getEndDate().toString() : "无").append("\n")
                        .append("  状态: ").append(plan.getStatus()).append("\n") // 0-未开始,1-进行中,2-已暂停,3-已取消,4-已完成
                        .append("  发布状态: ").append(plan.getPstatus()).append("\n") // 0-未发布,1-发布
                        .append("\n");
            }
        }

        // 查询所有维护记录
        List<MaintenanceRecord> maintenanceRecords = maintenanceRecordMapper.selectMaintenanceRecordList(new MaintenanceRecord());
        if (!maintenanceRecords.isEmpty()) {
            fullPromptBuilder.append("以下是维护记录：\n");
            for (MaintenanceRecord record : maintenanceRecords) {
                fullPromptBuilder.append("- 记录ID: ").append(record.getId()).append("\n")
                        .append("  计划ID: ").append(record.getPlanId()).append("\n")
                        .append("  设备ID: ").append(record.getDeviceId()).append("\n")
                        .append("  记录类型: ").append(record.getRecordType()).append("\n") // 1-维护记录,2-检查记录
                        .append("  记录内容: ").append(record.getRecordContent()).append("\n")
                        .append("  记录结果: ").append(record.getRecordResult()).append("\n") // 1-正常,2-异常,3-待确认
                        .append("  异常描述: ").append(record.getAbnormalDesc()).append("\n")
                        .append("  处理建议: ").append(record.getSuggestions()).append("\n")
                        .append("  记录时间: ").append(record.getRecordTime() != null ? record.getRecordTime().toString() : "无").append("\n")
                        .append("  记录人: ").append(record.getRecordBy()).append("\n")
                        .append("\n");
            }
        }

        // 查询所有维护人员分配记录
        List<MaintenanceAssign> maintenanceAssigns = maintenanceAssignMapper.selectMaintenanceAssignList(new MaintenanceAssign());
        if (!maintenanceAssigns.isEmpty()) {
            fullPromptBuilder.append("以下是维护人员分配记录：\n");
            for (MaintenanceAssign assign : maintenanceAssigns) {
                fullPromptBuilder.append("- 分配ID: ").append(assign.getId()).append("\n")
                        .append("  计划ID: ").append(assign.getPlanId()).append("\n")
                        .append("  用户ID: ").append(assign.getUserId()).append("\n")
                        .append("  分配类型: ").append(assign.getAssignType()).append("\n") // 1-负责人,2-实施人
                        .append("\n");
            }
        }

        // 添加聊天历史记录
        for (String historyEntry : chatHistory) {
            fullPromptBuilder.append(historyEntry.replace("AI:", "")).append("\n");
        }

        // 添加当前用户消息
        fullPromptBuilder.append("User: ").append(message).append("\n");

        return fullPromptBuilder.toString();
    }
}
